<template>
	<view class="login_box">
		<view class="text_login">
			<!-- logo -->
			<image class="login_logo"  src="../../static/images/logo1.png" alt="" />
			
			<!-- 表单区域 -->
			<view class="login_phone">
				<text>手机号</text>
				<input type="text" v-model="phone"  maxlength="11" />
			</view>
			<view class="login_code">
				<text>验证码</text>
				<input type="text" v-model="code" maxlength="4" />
				<view hover-class="touchOpacity" @click="getCode">{{codeText}}</view>
			</view>
			
			<!-- 登录按钮 -->
			<view class="login_but" hover-class="touchOpacity" >
				<text space="ensp" @click="toLogin">登    录</text> 
			</view>
		</view>
	</view>
</template>

<script>

	export default {
		data() {
			return {
				phone:'',
				code:'',
				codeText:'获取验证码',
				codeFlag:false
			}
		},
		methods: {
			// 登录
			async toLogin(){
				let phone = this.phone
				let code = this.code
				let sPhone = uni.getStorageSync('phone') || null;
				let sCode = uni.getStorageSync('code') || null;
				console.log(sCode);
				// 验证手机号
				if(phone != sPhone || sPhone == null || sPhone == ''){
					uni.showToast({
						title:'手机格式不正确',
						icon:'none'
					})
					return false
				}
				// 验证码
				if(code != sCode || sCode == null || sCode == ''){
					uni.showToast({
						title:'验证码不正确',
						icon:'none'
					})
					return false
				}
				
				let option = {
					url:'/api/smslogin',
					method:'POST',
					data:{
						phone:phone
					}
				}
				let res = await this.$http(option)
				if(res.data.code == 200){
					console.log(res);
					uni.setStorageSync('userInfo',res.data.list);
					uni.removeStorageSync('code');
					uni.removeStorageSync('phone');
					this.$store.commit('changeInfo',res.data.list);
					uni.showToast({
						title:res.data.msg,
						icon:'none'
					})
					setTimeout(() => {
						uni.switchTab({
							url:'/pages/mine/mine'
						})
					},1500)
				}else{
					uni.showToast({
						title:'登录失败',
						icon:'error'
					})
				}
			},
			async getCode(){
				let phone = this.phone
				let code = this.code
				if(!phone){
					uni.showToast({
						title:'手机号不能为空',
						icon:'none'
					})
				}
				let res = await this.$http({url:'/api/sms'});
				if(res.data.code == 200){
					uni.setStorageSync('code',res.data.list.code)
					uni.setStorageSync('phone',phone)
					console.log(res.data.list.code);
					let num = 5;
					let timer = setInterval(() => {
						num -- ;
						this.codeText = num + 's后获取验证';
						if(num < 1){
							clearInterval(timer);
							num = 5
							this.codeText = '获取验证码'
						}
					},1000)
				}else{
					uni.showToast({
						title:'获取验证码失败',
						icon:'none'
					})
				}
			}
		}
}
</script>

<style>
	/* 引入样式 */
	@import url("@/static/css/textlogin.css");
</style>
